package com.example.jones.test;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.util.CookbookImage;

public class DtlAdepter extends BaseAdapter {

    // 定义需要包装的JSONArray对象
    private JSONArray jsonArray;

    public DtlAdepter(JSONArray jsonArray) {
        this.jsonArray = jsonArray;
    }

    public int getCount() {
        return jsonArray.length();
    }

    public Object getItem(int position) {
        return jsonArray.optJSONObject(position);
    }

    public long getItemId(int position) {
        try {
            // 返回物品的ID
            return ((JSONObject) getItem(position)).getInt("id");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public View getView(int pot, View convertView, ViewGroup parent) {
        System.out.println("##################DtlAdepter ：getView" + pot);

        convertView = LayoutInflater.from(parent.getContext()).inflate(
                R.layout.dtl_list_item, null);

        ImageView iv_center = (ImageView) convertView
                .findViewById(R.id.iv_center);
        TextView dt_list_count = (TextView) convertView
                .findViewById(R.id.dt_list_count);
        TextView dt_list_step = (TextView) convertView
                .findViewById(R.id.dt_list_step);

        // 获取JSONArray数组元素
        try {
            dt_list_count.setText(((JSONObject) getItem(pot)).getString("NO"));
            dt_list_step.setText(((JSONObject) getItem(pot))
                    .getString("content"));

            CookbookImage cbimg = new CookbookImage();
            String pic = ((JSONObject) getItem(pot)).getString("pic");
            if (pic != null) {
                iv_center.setImageBitmap(cbimg.getmybitmap(pic));
            } else {

            }
        } catch (JSONException e) {
            System.out
                    .println("########DtlAdepter ：getView 获取JSONArray数组元素的属性出错！");
            e.printStackTrace();
        }
        return convertView;
    }

}
